{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(concurrent-processing)=\n",
    "# Concurrent processing\n",
    "\n",
    "Concurrent processing is typically used for serving of deep-learning models, where preparation steps and inference can be CPU/GPU heavy, or involving I/O. The concurrency modes are:\n",
    "- asyncio &mdash; Default. For I/O implemented using asyncio.\n",
    "- threading &mdash; For blocking I/O.\n",
    "- multiprocessing &mdash; For processing-intensive tasks.\n",
    "\n",
    "Additional configuration:\n",
    "- max_in_flight: Maximum number of events to be processed at a time (default 8)\n",
    "- retries: Maximum number of retries per event (default 0)\n",
    "- backoff_factor: Wait time in seconds before the first retry (default 1). Subsequent retries each wait twice long as the previous retry, up to a maximum of two minutes.\n",
    "- pass_context: If False, the `process_event` function is called with just one parameter (event). If True, the `process_event` function is called with two parameters (event, context). (Defaults to False)\n",
    "- full_event: Whether the event processor should receive and return Event objects (when True), or only the payload (when False). (Defaults to False)\n",
    "\n",
    "This example illustrates a multiprocess step to perform predictions.\n",
    "\n",
    "First define the processes:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import mlrun\n",
    "import mlrun.artifacts\n",
    "import storey\n",
    "import storey.steps\n",
    "import asyncio\n",
    "import time\n",
    "import numpy as np\n",
    "import pickle\n",
    "\n",
    "\n",
    "model_file = \"model.pkl\"\n",
    "\n",
    "\n",
    "class Predict:\n",
    "    def __init__(self):\n",
    "        self.model = pickle.load(open(model_file, \"rb\"))\n",
    "\n",
    "    def predict(self, body: dict):\n",
    "        print(\"predicting...\")\n",
    "        feats = np.asarray(body[\"inputs\"])\n",
    "        result: np.ndarray = self.model.predict(feats)\n",
    "        return result.tolist()\n",
    "\n",
    "\n",
    "predict = Predict().predict\n",
    "\n",
    "\n",
    "async def preprocess(event, context):\n",
    "    context.logger.info(\"preprocessing...\")\n",
    "    await asyncio.sleep(0.1)\n",
    "    return event\n",
    "\n",
    "\n",
    "def postprocess(event, context):\n",
    "    context.logger.info(\"postprocessing...\")\n",
    "    time.sleep(0.1)\n",
    "    return event"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Define the project and the function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "project_name = \"concurrent-prediction\"\n",
    "project = mlrun.get_or_create_project(project_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "function = project.set_function(\n",
    "    name=\"test\",\n",
    "    kind=\"serving\",\n",
    "    image=\"mlrun/mlrun\",\n",
    ")\n",
    "\n",
    "function.spec.build.commands = [\n",
    "    \"wget https://github.com/mlrun/mlrun/raw/development/tests/system/model_monitoring/assets/model.pkl\",\n",
    "]\n",
    "\n",
    "graph = function.set_topology(\"flow\", engine=\"async\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And, finally, the multi-process step:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "graph.to(\n",
    "    \"storey.ConcurrentExecution\",\n",
    "    \"preprocess\",\n",
    "    _event_processor=\"preprocess\",\n",
    "    pass_context=True,\n",
    "    max_in_flight=8,\n",
    ").to(\n",
    "    \"storey.ConcurrentExecution\",\n",
    "    \"prediction\",\n",
    "    _event_processor=\"predict\",\n",
    "    concurrency_mechanism=\"multiprocessing\",\n",
    "    max_in_flight=2,\n",
    ").to(\n",
    "    \"storey.ConcurrentExecution\",\n",
    "    \"postprocess\",\n",
    "    _event_processor=\"postprocess\",\n",
    "    concurrency_mechanism=\"threading\",\n",
    "    pass_context=True,\n",
    "    max_in_flight=8,\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
